package cn.edu.xhu.library_management.iot.websocket;

import cn.edu.xhu.library_management.iot.dto.ControlMachine;
import cn.edu.xhu.library_management.iot.dto.MachineControl;
import cn.edu.xhu.library_management.iot.dto.MachineJson;
import cn.edu.xhu.library_management.iot.mqtt.client.MqttSendClient;
import com.alibaba.fastjson2.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.net.http.WebSocket;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author: MMJ
 * @Date: 2023 - 04 - 30
 * @Description: websocket的处理类。作用相当于HTTP请求中的controller
 */
@Component
@ServerEndpoint("/lm_iot/socket")
public class WebSocketServer {

    private static MqttSendClient sendClient;

    @Autowired // setter注入
    public  void setSendClient(MqttSendClient sendClient) {
        WebSocketServer.sendClient = sendClient;
    }

    private Session session;
    //存放websocket的集合（本次demo不会用到，聊天室的demo会用到）
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();
    //前端请求时一个websocket时
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
        System.out.println("【websocket消息】有新的连接, 总数:"+webSocketSet.size());
    }

    //前端关闭时一个websocket时
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        System.out.println("【websocket消息】连接断开, 总数:{}"+webSocketSet.size());
    }

    //前端向后端发送消息
    @OnMessage
    public void onMessage(String message) {
        MachineJson json = new MachineJson();
        if (message.equals("onLed")){
            json.setTarget("LED");
            json.setValue(ControlMachine.LED_ON);
            sendClient.publish(false,"/SmartLibrary/sub", JSON.toJSONString(json));
        }else if (message.equals("offLed")){
            json.setTarget("LED");
            json.setValue(ControlMachine.LED_OFF);
            sendClient.publish(false,"/SmartLibrary/sub", JSON.toJSONString(json));
        } else if (message.equals("onBeep")) {
            json.setTarget("BEEP");
            json.setValue(ControlMachine.BEEP_ON);
            sendClient.publish(false,"/SmartLibrary/sub", JSON.toJSONString(json));
        }else if (message.equals("offBeep")){
            json.setTarget("BEEP");
            json.setValue(ControlMachine.BEEP_OFF);
            sendClient.publish(false,"/SmartLibrary/sub", JSON.toJSONString(json));
        } else if (message.equals("onAir")) {
            json.setTarget("Fan");
            json.setValue(ControlMachine.FAN_ON);
            sendClient.publish(false,"/SmartLibrary/sub", JSON.toJSONString(json));
        } else if (message.equals("offAir")) {
            json.setTarget("Fan");
            json.setValue(ControlMachine.FAN_OFF);
            sendClient.publish(false,"/SmartLibrary/sub", JSON.toJSONString(json));
        }else if (message.equals("onWindow")){
            json.setTarget("Windows");
            json.setValue(ControlMachine.WINDOW_ON);
            sendClient.publish(false,"/SmartLibrary/sub", JSON.toJSONString(json));
        } else if (message.equals("offWindow")) {
            json.setTarget("Windows");
            json.setValue(ControlMachine.WINDOW_OFF);
            sendClient.publish(false,"/SmartLibrary/sub", JSON.toJSONString(json));
        }
        System.out.println("【websocket消息】收到客户端发来的消息:"+MachineControl.LED_ON.getMachine());
    }

    //新增一个方法用于主动向客户端发送消息
    public static void sendMessage(String message) {
        for (WebSocketServer webSocket: webSocketSet) {
            System.out.println("【websocket消息】广播消息, message={}"+message);
            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
